#include "RequestManager.h"
const int MaxTaskCount = 100;
RequestManager::RequestManager(/* args */): requestQueue_(MaxTaskCount)
{
    std::call_once(flagonce_, [this]
                   { StartThread(); });
}

RequestManager::~RequestManager()
{
    std::call_once(flagonce_stop_, [this]
                   { StopThread(); });
}

void RequestManager::StartThread()
{
    running_ = true;
    thread_ = std::thread(&RequestManager::ThreadRunning, this);
}

void RequestManager::StopThread()
{
    running_ = false;
    thread_.join();
}

void RequestManager::ThreadRunning()
{
    while (running_)
    {
        std::list<std::shared_ptr<Request>> list;
        requestQueue_.Take(list);

        for (auto &task : list)
        {
            if (!running_)
                return;

            // std::this_thread::sleep_for(std::chrono::milliseconds(3000));
            top_request_ = task;
            top_request_->DoRequest();
        }
    }
}

void RequestManager::AddRequest(std::shared_ptr<Request> spRequest)
{
    requestQueue_.Put(spRequest);
}

void RequestManager::SetRequest_GetResponse(uint16_t serial)
{
    if (nullptr == top_request_)
    {
        return;
    }
    
    if (serial == top_request_->u16Sserial_)
    {
        top_request_->GetResponse();
    }
    
}